package com.humanminoritygame.model;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class HibernateRoomRepo extends HibernateGenericRepo implements RoomRepo{
  @Autowired
  public HibernateRoomRepo(SessionFactory sessionFactory) {
    setSessionFactory(sessionFactory);
  }
  
  @Override
  public Room addRoom(Room room) {
    Session session = getSession();
    session.save(room);
    session.flush();
    return room;
  }
  
  @SuppressWarnings("unchecked")
  @Override
  public Set<Room> getRoomsByCategory(Category category) {
    Set<Room> rooms = new HashSet<Room>();
    Query q = getSession().createQuery("SELECT r FROM Room  r WHERE r.category =:id");
    q.setEntity("id",category);
    rooms.addAll(q.list());
    return rooms;
  }

  @SuppressWarnings("unchecked")
  @Override
  public SortedSet<Room> getRooms() {
    SortedSet<Room> rooms = new TreeSet<Room>();
    rooms.addAll(getSession().createQuery("SELECT r FROM Room  r").list());
    return rooms;
  }

  @SuppressWarnings("unchecked")
  @Override
  public SortedSet<Room> getClosedRooms() {
    SortedSet<Room> rooms = new TreeSet<Room>();
    rooms.addAll(getSession().createQuery("SELECT r FROM Room  r WHERE r.state = 'CLOSED' ").list());
    return rooms;
  }
  
  @Override
  public void removeRoom(Room room) {
    getSession().delete(room);
  }

  @Override
  public Room getRoomById(Long roomId) {
    return (Room)getSession().get(Room.class, roomId);
  }

  @SuppressWarnings("unchecked")
  @Override
  public Set<Room> getOpenRooms() {
    Set<Room> rooms = new HashSet<Room>();
    rooms.addAll(getSession().createQuery("SELECT r FROM Room r WHERE r.state = 'OPEN' ").list());
    return rooms;
  }

  @SuppressWarnings("unchecked")
  @Override
  public AnswerType getLastRoomResult(Long roomId) {
    Room room = this.getRoomById(roomId);
    if(room == null){
      return null;
    }
    
    Query q = getSession().createQuery("SELECT round FROM Round round WHERE round.room=:room AND round.summary.answer IS NOT NULL ORDER BY startDate DESC");
    q.setEntity("room",room);
    List<Round> rounds = q.list();
    if(rounds.isEmpty()){
      return null;
    }
    return ((Round)(q.iterate().next())).getSummary().getAnswer();
  }
}
